<script setup lang="ts">
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";

import { createRoom } from "@/api/module/room.api.ts";

import formRules from "./form-rules.ts";

import type { FormInst } from "naive-ui";
import { ROOM_CAPACITY_RAGE_MAX, ROOM_CAPACITY_RAGE_MIN } from "@/pages/room/constant/validation-constants.ts";
import { useRequest } from "@/api/utils.ts";

const router = useRouter();

const formRef = ref<FormInst>();

const formData = reactive({
    name: "",
    password: "",
    capacity: 10
});

const { response, request } = useRequest(createRoom);

function handleBack() {
    router.back();
}

function handleCreate() {
    formRef.value?.validate((errors) => {
        if (!errors) {
            request({
                name: formData.name,
                password: formData.password || undefined,
                capacity: formData.capacity
            }).then(() => {
                // 创建成功返回上一页
                handleBack();
            });
        }
    });
}

</script>

<template>
    <div class="h-full flex flex-col p-7 gap-10">
        <!-- 标题头 -->
        <header class="flex-shrink-0 flex items-center gap-2">
            <n-icon :size="30" @click="handleBack">
                <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path d="M800 480H268.8l233.6-233.6c12.8-12.8 12.8-32 0-44.8-12.8-12.8-32-12.8-44.8 0l-284.8 288c-12.8 12.8-12.8 32 0 44.8h3.2l284.8 288c6.4 6.4 16 9.6 22.4 9.6 9.6 0 16-3.2 22.4-9.6 12.8-12.8 12.8-32 0-44.8L272 544H800c19.2 0 32-12.8 32-32s-16-32-32-32z"></path></svg>
            </n-icon>
            <h1 class="text-xl font-bold">创建房间</h1>
        </header>

        <n-scrollbar class="flex-grow">
            <n-form ref="formRef" :rules="formRules" :model="formData" size="large" :disabled="response.waiting">
                <!-- 房间名称 -->
                <n-form-item label="房间名称" path="name">
                    <n-input v-model:value="formData.name" clearable placeholder="留空使用默认"/>
                </n-form-item>
                <!-- 房间密码 -->
                <n-form-item label="房间密码" path="password">
                    <n-input v-model:value="formData.password" clearable type="password" placeholder="留空则不设置"/>
                </n-form-item>
                <!-- 房间人数 -->
                <n-form-item label="房间最大人数" path="capacity">
                    <div class="w-full flex items-center gap-5">
                        <n-input-number class="flex-grow" v-model:value="formData.capacity" :min="ROOM_CAPACITY_RAGE_MIN" :max="ROOM_CAPACITY_RAGE_MAX" placeholder="0~50"/>
                    </div>
                </n-form-item>
            </n-form>
        </n-scrollbar>
        <div class="flex-shrink-0">
            <n-button block size="large" type="primary" :loading="response.waiting" @click="handleCreate">创 建</n-button>
        </div>
    </div>
</template>

<style scoped>

</style>